<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import StudentSignInfo from './components/StudentSignInfo.vue'
import type { StudentInfoItem, StudentInfoParams } from '@/types/studentInfo'
import { getStudentInfoList, addStudyRecord, batchSignIn } from '@/services/studentInfo.ts'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import UniFab from '@dcloudio/uni-ui/lib/uni-fab/uni-fab.vue'
import { useMemberStore } from '@/stores'
import { config } from '@/global'

const studentInfoList = ref<StudentInfoItem[]>([])
const hasMoreInfo = ref(true)
// 是否加载中标记
const isLoading = ref(false)
const studentInfoParams = ref<StudentInfoParams>({ pageNum: 1, pageSize: 10 })
// 获取消息列表
const getStudentInfoListData = async (pageParams: StudentInfoParams) => {
  // 如果是下拉刷新，清空现有数据
  if (pageParams.pageNum === 1) {
    studentInfoList.value = []
    hasMoreInfo.value = true
  }

  // 如果没有更多数据，直接返回
  if (!hasMoreInfo.value) {
    return
  }

  try {
    const res = await getStudentInfoList(pageParams)
    // 添加数据
    if (pageParams.pageNum === 1) {
      studentInfoList.value = res.data
    } else {
      studentInfoList.value = [...studentInfoList.value, ...res.data]
    }
    // 判断是否还有更多数据
    hasMoreInfo.value = res.data.length === pageParams.pageSize
    // 更新页码
    studentInfoParams.value.pageNum = pageParams.pageNum
  } catch (error) {
    console.error('获取学生列表失败:', error)
  }
}

// 加载数据
const loadData = async (classRoomId: number) => {
  isLoading.value = true
  studentInfoParams.value.roomId = classRoomId
  await getStudentInfoListData(studentInfoParams.value) // 重置为第一页
  isLoading.value = false
}

// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
// 下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  // 根据当前标签刷新对应数据
  studentInfoParams.value.pageNum = 1
  studentInfoParams.value.pageSize = 10
  await getStudentInfoListData(studentInfoParams.value)
  isTriggered.value = false
}
// 上拉加载更多
const handleLoadMore = () => {
  if (hasMoreInfo.value) {
    studentInfoParams.value.pageNum = (studentInfoParams.value.pageNum ?? 1) + 1
    getStudentInfoListData(studentInfoParams.value)
  }
}

onLoad((options: any) => {
  // 首次加载数据
  loadData(options.classRoomId)
})
// 添加弹窗控制变量
const popupTitle = ref('记录上课信息')
const studyStatus = ref(1)
const scheduleId = ref(1)
const recordPopup = ref<InstanceType<typeof UniPopup> | null>(null)
const selectImageList = ref<string[]>([])
// 表单数据
const formData = ref({
  classTime: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().slice(0, 8),
  comment: '',
  score: 5,
  activityScore: 5,
  participationScore: 5,
  images: [] as string[], // 新增图片数组
})
// 实现弹窗打开方法
const openRecordPopup = (status: number, studentScheduleId: number) => {
  scheduleId.value = studentScheduleId
  studyStatus.value = status
  popupTitle.value =
    status === 4
      ? '课堂点评'
      : status === 2
      ? '记录请假信息'
      : status === 3
      ? '记录缺勤信息'
      : '记录上课信息'
  formData.value = {
    classTime: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().slice(0, 8),
    comment: '',
    score: status === 4 ? 5 : 0,
    activityScore: 5,
    participationScore: 5,
    images: [], // 清空图片数组
  }
  recordPopup.value?.open()
}
// 新增文件选择处理
const onFileSelect = (e: any) => {
  // 获取选择的图片临时文件路径
  const tempFilePaths = e.tempFilePaths || e.detail?.tempFilePaths
  if (!tempFilePaths) {
    console.error('未获取到图片路径:', e)
    return
  }

  // 计算添加后的总数
  const totalCount = selectImageList.value.length + tempFilePaths.length

  // 如果超过9张，给出提示
  if (totalCount > 9) {
    uni.showToast({ title: '最多只能上传9张图片', icon: 'none' })
  }

  // 更新图片数组，确保不超过9张
  const newImages = [...selectImageList.value, ...tempFilePaths].slice(0, 9)
  selectImageList.value = newImages

  // 添加调试信息
  console.log('选择的图片路径:', selectImageList.value)
}

// 新增文件删除处理
const onFileDelete = (e: any) => {
  // 打印事件参数，查看结构
  console.log('删除事件参数:', e)
  // 确保正确获取索引
  const index = e.index
  if (typeof index !== 'number') {
    console.error('无法获取删除索引:', e)
    return
  }
  selectImageList.value.splice(index, 1)
  console.log('删除后的图片数组:', selectImageList.value)
}

// 实现弹窗关闭方法
const closeRecordPopup = () => {
  recordPopup.value?.close()
}

// 实现提交方法
const submitRecord = async () => {
  // 先处理图片上传
  let imageUrls: string[] = []
  console.log(selectImageList.value, '21321')
  if (selectImageList.value.length > 0) {
    // 这里需要实现图片上传逻辑，假设使用uni.uploadFile
    for (const filePath of selectImageList.value) {
      const uploadResult = await uploadImage(filePath)
      if (uploadResult) {
        imageUrls.push(uploadResult)
      }
    }
  }
  console.log(imageUrls, '21321')
  const res = await addStudyRecord({
    studyStatus: studyStatus.value,
    scheduleId: scheduleId.value,
    studyTime: formData.value.classTime,
    studyRecord: formData.value.comment,
    score: formData.value.score,
    activityScore: formData.value.activityScore,
    participationScore: formData.value.participationScore,
    attachment: imageUrls.join(';'),
  })
  if (res.code == 200) {
    uni.showToast({ title: '记录成功', icon: 'success' })
    closeRecordPopup()
    onRefresherrefresh()
  } else {
    uni.showToast({ title: res.msg || '记录失败', icon: 'error' })
  }
}

const memberStore = useMemberStore()
// 新增图片上传函数
const uploadImage = (filePath: string): Promise<string | null> => {
  return new Promise((resolve) => {
    // 获取token
    const token = memberStore.profile?.token || ''

    uni.uploadFile({
      url: '/wechat/student/uploadAttachment', // 替换为实际的上传API
      filePath: filePath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        Authorization: `Bearer ${token}`, // 携带token
      },
      success: (res) => {
        console.log(res)
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data)
          resolve(data.url)
        } else {
          resolve(null)
        }
      },
      fail: () => {
        resolve(null)
      },
    })
  })
}

// 新增悬浮按钮相关状态
const fabShow = ref(true)
// 一键签到功能
const oneKeySignIn = async () => {
  if (studentInfoList.value.length === 0) {
    uni.showToast({ title: '暂无学生数据', icon: 'none' })
    return
  }

  // 显示确认框
  uni.showModal({
    title: '确认一键签到',
    content: `确定要为 ${studentInfoList.value.length} 名学生进行一键签到吗？`,
    success: async (res) => {
      if (res.confirm) {
        // 用户点击确定，执行签到逻辑
        try {
          const studentIds = studentInfoList.value.map((student) => student.id)
          const res = await batchSignIn({
            studentScheduleIds: studentIds.join(','),
          })

          if (res.code === 200) {
            uni.showToast({ title: '一键签到成功', icon: 'success' })
            onRefresherrefresh()
          } else {
            uni.showToast({ title: res.msg || '签到失败', icon: 'error' })
          }
        } catch (error) {
          console.error('一键签到失败:', error)
          uni.showToast({ title: '签到失败', icon: 'error' })
        }
      } else if (res.cancel) {
        // 用户点击取消，不执行操作
        console.log('用户取消一键签到')
      }
    },
    fail: (err) => {
      console.error('显示确认框失败:', err)
    },
  })
}

// 添加新的事件处理函数
const handleMenuButtonClick = (e: any) => {
  console.log('菜单按钮点击索引:', e.index)
  if (e.index === 0) {
    oneKeySignIn()
  }
}
</script>

<template>
  <!-- 页面头部 -->
  <!-- <view class="page-header">
    <text class="header-title">学生管理</text>
  </view> -->
  <!-- 滚动容器 -->
  <scroll-view
    :enable-back-to-top="true"
    :refresher-enabled="true"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="handleLoadMore"
    class="message-list"
    :scroll-y="true"
  >
    <StudentSignInfo
      v-for="student in studentInfoList"
      :key="student.id"
      :studentInfo="student"
      @openRecordPopup="openRecordPopup"
    />
    <!-- 空状态显示 -->
    <view class="empty-state" v-if="studentInfoList.length === 0 && !isLoading">
      <image class="empty-icon" src="@/static/images/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无相关学生数据</text>
      <button class="empty-button" @click="onRefresherrefresh">刷新</button>
    </view>
    <!-- 加载中状态 -->
    <!-- <view class="loading-state" v-if="isLoading">
      <uni-loading type="spinner" size="24"></uni-loading>
      <text class="loading-text">加载中...</text>
    </view> -->
  </scroll-view>

  <!-- 新增记录弹窗 -->
  <uni-popup
    ref="recordPopup"
    type="center"
    :mask-click="false"
    :safe-area="true"
    class="record-popup"
  >
    <view class="popup-content">
      <view class="popup-header">
        <text class="popup-title">{{ popupTitle }}</text>
        <uni-icons type="close" size="24" @click="closeRecordPopup"></uni-icons>
      </view>
      <uni-forms ref="recordForm" :modelValue="formData" label-width="160rpx">
        <uni-forms-item label="上课时间" required>
          <uni-datetime-picker
            type="datetime"
            v-model="formData.classTime"
            placeholder="选择上课时间"
          />
        </uni-forms-item>
        <uni-forms-item label="上课评价">
          <uni-easyinput
            type="textarea"
            v-model="formData.comment"
            placeholder="请输入上课评价"
            :maxlength="200"
            class="textarea-input"
          />
        </uni-forms-item>
        <uni-forms-item label="综合评分" v-if="studyStatus == 4">
          <uni-rate v-model="formData.score" :max="5" :min="1" :star-size="36" color="#FF7D00" />
        </uni-forms-item>
        <uni-forms-item label="活跃度" v-if="studyStatus == 4">
          <uni-rate
            v-model="formData.activityScore"
            :max="5"
            :min="1"
            :star-size="36"
            color="#FF7D00"
          />
        </uni-forms-item>
        <uni-forms-item label="参与度" v-if="studyStatus == 4">
          <uni-rate
            v-model="formData.participationScore"
            :max="5"
            :min="1"
            :star-size="36"
            color="#FF7D00"
          />
        </uni-forms-item>
        <!-- 图片上传 -->
        <uni-forms-item label="上传图片" v-if="studyStatus == 4">
          <uni-file-picker
            v-model="formData.images"
            file-mediatype="image"
            mode="grid"
            :limit="9"
            :sizeType="['compressed']"
            :max-size="5 * 1024 * 1024"
            @select="onFileSelect"
            @delete="onFileDelete"
            class="file-picker"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-forms>
      <view class="popup-footer">
        <button type="default" size="mini" @click="closeRecordPopup">取消</button>
        <button type="primary" size="mini" @click="submitRecord">提交</button>
      </view>
    </view>
  </uni-popup>

  <!-- 悬浮按钮 -->
  <uni-fab
    ref="fab"
    :show="fabShow"
    horizontal="right"
    :content="[
      {
        iconPath: config.baseURL + '/profile/upload/checkmark.png',
        selectedIconPath: config.baseURL + '/profile/upload/checkmark.png',
        text: '一键签到',
        active: false,
      },
    ]"
    @trigger="handleMenuButtonClick"
  ></uni-fab>
</template>

<style scoped lang="scss">
/* 滚动容器样式 */
.message-list {
  padding: 20rpx 0;
  background-color: $student-bg-color;
  min-height: calc(100vh - 100rpx);
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: $student-text-tertiary;
  margin-bottom: 30rpx;
}

.empty-button {
  background-color: $student-primary-color;
  color: white;
  border-radius: 44rpx;
  padding: 0 60rpx;
  font-size: 28rpx;
}

/* 加载中状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: $student-text-tertiary;
  margin-top: 16rpx;
}

/* 弹窗样式 */
.record-popup {
  display: flex;
  align-items: flex-end;
}

.popup-content {
  width: 100% !important;
  max-width: 700rpx;
  margin: 0 auto;
  padding: 30rpx;
  background-color: $student-card-bg;
  border-radius: 20rpx 20rpx 0 0;
  box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid $student-border-color;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: $student-text-primary;
}

.textarea-input {
  min-height: 160rpx;
  border: 1rpx solid $student-border-color;
  border-radius: 8rpx;
  padding: 20rpx;
}

.file-picker {
  margin-top: 10rpx;
}

.popup-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
  margin-top: 40rpx;
}

.popup-footer button {
  border-radius: 44rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
  height: 88rpx;
  line-height: 88rpx;
}

/* 按钮样式优化 */
.popup-footer button:first-child {
  background-color: #f5f7fa;
  color: $student-text-secondary;
}

/* 评分组件样式 */
.uni-rate {
  margin-top: 8rpx;
}

/* 批量签弹窗样式 */
.batch-popup {
  display: flex;
  align-items: center;
  justify-content: center;
}

.batch-popup-content {
  width: 90%;
  max-width: 600rpx;
  background-color: $student-card-bg;
  border-radius: 20rpx;
  box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.1);
  padding: 30rpx;
}

.batch-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid $student-border-color;
}

.batch-popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: $student-text-primary;
}

.batch-popup-body {
  max-height: 500rpx;
  overflow-y: auto;
}

.select-all-btn {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid $student-border-color;
}

.select-all-btn text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: $student-text-primary;
}

.selected-count {
  margin-left: auto;
  font-size: 26rpx;
  color: $student-text-secondary;
}

.student-list {
  max-height: 400rpx;
}

.student-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid $student-border-color;
}

.checkbox {
  margin-right: 20rpx;
}

.student-info {
  flex: 1;
}

.student-name {
  font-size: 28rpx;
  color: $student-text-primary;
}

.student-id {
  font-size: 24rpx;
  color: $student-text-secondary;
}

.batch-popup-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
  margin-top: 30rpx;
}

.batch-popup-footer button {
  border-radius: 44rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
  height: 88rpx;
  line-height: 88rpx;
}

/* 悬浮按钮样式 */
.uni-fab {
  --fab-bg-color: $student-primary-color;
  --fab-menu-bg-color: $student-primary-color;
}
</style>
